<?php
/**
 * Created by PhpStorm.
 * User: Inhere
 * Date: 2015/2/7
 * Time: 21:28
 * Use :
 * File: TraitUseAlias.php
 */

namespace ulue\libs\traits;


trait TraitUseAlias
{
    protected $_aliases       = [];
    protected $lockedAliases = [];
    protected $id            = '';

    /**
     * state description lock free
     * @param string $alias 别名
     * @param string $id 真实的值
     * @throws \DRuntimeException
     * @return $this
     */
    public function alias($alias, $id='')
    {
        if ( !$id ) {
            $id = $this->id;
        }

        if ( !$id || !is_string($id) ) {
            throw new \InvalidArgumentException(sprintf(
                'The 2th parameter must be of type string is not empty, %s given',
                gettype($id)
            ));
        }

        if ( in_array($alias, $this->lockedAliases)) {
            throw new \DRuntimeException(sprintf('别名：%s , 已被系统锁定。请设置其他名称。',$alias));
        }

        if ( !isset($this->_aliases[$alias]) ) {
            $this->_aliases[$alias] = trim($id);
        }

        return $this;
    }

    /**
     * @param $alias
     * @return mixed
     */
    public function resolveAlias($alias)
    {
        return isset($this->_aliases[$alias]) ? $this->_aliases[$alias]: $alias;
    }

    /**
     * 载入别名设置
     * @param array $aliases
     * @return $this
     */
    public function loadAliases(array $aliases)
    {
        foreach ($aliases as $alias => $path) {
            $this->alias($alias, $path);
        }

        return $this;
    }

    /**
     * @param $alias
     * @return mixed
     */
    public function isAlias($alias)
    {
        return isset($this->_aliases[$alias]) ? $this->_aliases[$alias]: false;
    }

    /**
     * @param array $aliases
     * @return $this
     */
    public function lockAliases(array $aliases)
    {
        foreach ($aliases as $alias) {
            $this->lockedAliases[] = $alias;
        }

        return $this;
    }

    /**
     * @param $alias
     */
    public function lockAlias($alias)
    {
        if ( $alias && !isset($this->lockedAliases[$alias]) )
        {
            $this->lockedAliases[] = $alias;
        }
    }

    /**
     * @param $alias
     * @return mixed
     */
    public function isLockedAlias($alias)
    {
        return isset($this->lockedAliases[$alias]) ? $this->lockedAliases[$alias]: false;
    }

    /**
     * @return array $_aliases
     */
    public function getAliases()
    {
        return $this->_aliases;
    }

    public function getLockedAliases()
    {
        return $this->lockedAliases;
    }

    /**
     * @param array $lockedAliases
     */
    public function setLockedAliases($lockedAliases)
    {
        $this->lockedAliases = $lockedAliases;
    }
}